const Version = function () {};
const errors = require('../../errors/index');
Version.prototype.use = function (options) {
    this._header = options.header.toLowerCase() || 'accept';
    this._grab = options.grab || /vnd.mycompany.com\+json; version=(\d+)(,|$)/;
    this._error = options.error || 406;
};
const has_matching_route = function (router, path, method) {
    return router.stack.some(function (layer) {
        if (layer.name === 'router' && layer.match(path)) {
            const layer_path = layer.regexp.exec(path)[0];
            const sub_path = path.substr(layer_path.length);
            return has_matching_route(layer.handle, sub_path, method);
        }
        if (!layer.route) {
            return false;
        }
        const matches_method = layer.route.methods._all || Boolean(layer.route.methods[method]);
        return layer.match(path) && matches_method;
    });
};
Version.prototype.reroute = function (min_version, reroute_map) {
    const header = this._header;
    const grab = this._grab;
    const error = this._error;
    return function (req, res, next) {
        let header_value = req.headers[header];
        //兼容旧版本 旧版本没有传Accept头部
        if (typeof header_value === 'undefined') {
            header_value = '1.0';
        }
        // console.log(header_value)
        if (header_value < min_version) {
            return next(new errors.BadRequestError('版本号过低, 请下载最新版本', {
                version: header_value
            }))
        }
        const match = grab.exec(header_value);
        const path = req.path;
        const method = req.method.toLowerCase();
        let route_handler_exist = false;
        const versions = Object.keys(reroute_map).reverse();
        for (let i = 0; i < versions.length; i++) {
            const version = versions[i];
            const router = reroute_map[version];
            if (has_matching_route(router, path, method)) {
                route_handler_exist = true;
                if (match && match[1] >= version) {
                    return router(req, res, next);
                }
            }
        }
        if (route_handler_exist) {
            return next(error);
        }
        return next();
    };
};
exports = module.exports = new Version();
